package com.topcent.tioxyc.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.cc.MaterialVOCC;
import com.topcent.tioxyc.pojo.vo.DeliveryDocumentVO;
import com.topcent.tioxyc.pojo.vo.DepartmentVO;
import com.topcent.tioxyc.pojo.vo.Wuliao01VO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/4/10 13:36
 * @Description: 2025-04-10创建test类
 */
@Slf4j
@RestController
public class CcDeliveryDocumentsDataController {
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;

    /**
     * 交货单数据-简道云
     *
     * @return
     */
    @GetMapping("deliveryDocumentsData")
    public String deliveryDocumentsData() {
        String appId = "67f8aa2676b9b3942c49035f";
        String entryId = "67f8aa542669a40210bc7655";
        Header[] headers = ConnmeUtils.createHeaders();
        // 获取用户人员信息
        Map<String ,Object> person =new HashMap<>();
        person.put("dept_no", 1);
        person.put("has_child", true);
        JSONObject personResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/user/list", headers, JSONUtil.toJsonStr(person));
        String personData = personResult.getStr("users");
        JSONArray personObjects = JSONUtil.parseArray(personData);
        List<Assignee> personList = JSONUtil.toList(personObjects, Assignee.class);
        Map<String, String> userNameMap = personList.stream()
                .collect(Collectors.toMap(Assignee::getName, Assignee::getUsername, (v1, v2) -> v1));
        // 获取销售部门信息
        Map<String ,Object> cond =new HashMap<>();
        cond.put("dept_no", 1);
        cond.put("has_child", true);
        JSONObject deptResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/list", headers, JSONUtil.toJsonStr(cond));
        String data = deptResult.getStr("departments");
        JSONArray objects = JSONUtil.parseArray(data);
        List<DepartmentVO> deptList = JSONUtil.toList(objects, DepartmentVO.class);
        Map<String, Integer> deptMap = deptList.stream()
                .collect(Collectors.toMap(DepartmentVO::getName, DepartmentVO::getDept_no, (v1, v2) -> v1));
        //批量删除简道云数据
        ConnmeUtils.selectAndDeleteList(headers, appId, entryId, "_widget_1744600670162");
        // 获取原始数据
        List<DeliveryDocumentsEntity> originalData = yy1KpiMapper.selecDeliveryDocumentsDatatAll();
        // 创建新集合存放处理后的数据
        List<DeliveryDocumentsEntity> processedData = new ArrayList<>();

        // 用于记录已出现的 a|b|c 组合
        Set<String> seenKeys = new HashSet<>();

        for (DeliveryDocumentsEntity doc : originalData) {
            // 假设字段名为 a、b、c，请根据你实体类实际字段名调整
            String key = doc.getReferenceSDDocumentItem() + "|" + doc.getReferenceSDDocument() + "|" + doc.getDeliveryDocument();

            if (seenKeys.add(key)) { // 如果这个组合是第一次出现，就添加
                processedData.add(doc);
            }
        }
        // 获取 销售-物料 数据
        List<YY1_KPI> orderMList = yy1KpiMapper.selectOrderM();

        // 初始化Map，键为 "SalesDocument-Material"，值为 YY1_Brand_SDI
        Map<String, Boolean> salesMaterialToBrandMap = orderMList.stream()
                .collect(Collectors.toMap(
                        // 键生成逻辑：SalesDocument-Material（处理空值）
                        kpi -> {
                            String salesDocument = kpi.getSalesDocument() == null ? "" : kpi.getSalesDocument();
                            String material = kpi.getMaterial() == null ? "" : kpi.getMaterial();
                            return salesDocument + "-" + material;
                        },
                        // 值生成逻辑：YY1_Brand_SDI（null 时保留 null）
                        YY1_KPI::getYY1_Brand_SDI,
                        // 键重复时的处理：保留后面的值（与原代码 put 覆盖逻辑一致）
                        (existingValue, newValue) -> newValue
                ));

        // 获取物料-大类
        // 固定物料大类：编码 -> 名称
        Map<String, String> materialMapZ = new HashMap<>();
        materialMapZ.put("Z101", "基础五金");
        materialMapZ.put("Z102", "收纳五金");
        materialMapZ.put("Z103", "功能五金");
        materialMapZ.put("Z104", "装潢五金"); // 修正“装潢五余”为“装潢五金”（推测笔误）
        materialMapZ.put("Z105", "配件");
        materialMapZ.put("Z106", "包材");

        String appIdMaterial = "668c9750508d1d2bf336211a";
        String entryIdMaterial = "668c98146b86173be43e6a21";
        List<MaterialVOCC> materialVOCCList = ConnmeUtils.getJianDaoYunData(headers, appIdMaterial, entryIdMaterial, MaterialVOCC.class);

        Map<String, String> materialMap = new HashMap<>();
        for (MaterialVOCC vo : materialVOCCList) {
            String originalCode = vo.get_widget_1720490004612(); // 物料编码
            String newCode = vo.get_widget_1720490004647(); // Z101
            if (StringUtils.isNotBlank(originalCode) && StringUtils.isNotBlank(newCode) ) {
                materialMap.put(originalCode, materialMapZ.get(newCode));
            }
        }

        // 物料分类
        Map<String, String> bToFLMap = materialVOCCList.stream()
                .filter(customer ->
                        customer.get_widget_1720490004612() != null && // 过滤键为null
                                customer.get_widget_1720490004631() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(MaterialVOCC::get_widget_1720490004612, MaterialVOCC::get_widget_1720490004631, (v1, v2) -> v1)); // key重复取第一个

        // 物料型号
        Map<String, String> bToXHMap = materialVOCCList.stream()
                .filter(customer ->
                        customer.get_widget_1720490004612() != null && // 过滤键为null
                                customer.get_widget_1721371578612() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(MaterialVOCC::get_widget_1720490004612, MaterialVOCC::get_widget_1721371578612, (v1, v2) -> v1)); // key重复取第一个

        //客户主数据集合
        List<Customer> customerList = getCustomerList();
        // 物料集合
        List<Wuliao01VO> wuliao01VOList = selectList();
        // 1. 将 wuliao01VOList 先转换为 Map，以 b 字段为 key，c 字段为 value，提高查找效率
        Map<String, String> bToCMap = wuliao01VOList.stream()
                .filter(customer ->
                        customer.get_widget_1720490004612() != null && // 过滤键为null
                                customer.get_widget_1720490004614() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Wuliao01VO::get_widget_1720490004612, Wuliao01VO::get_widget_1720490004614, (v1, v2) -> v1)); // key重复取第一个

        //建档日期
        Map<String, Date> bToTimeMap = customerList.stream()
                .filter(customer ->
                        customer.get_widget_1722305048887() != null && // 过滤键为null
                                customer.get_widget_1733204191654() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Customer::get_widget_1722305048887, Customer::get_widget_1733204191654, (v1, v2) -> v1)); // key重复取第一个

        // 国家名称
        Map<String, String> bToCountryMap = customerList.stream()
                .filter(customer ->
                        customer.get_widget_1722305048887() != null && // 过滤键为null
                                customer.get_widget_1722233514707() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Customer::get_widget_1722305048887, Customer::get_widget_1722233514707, (v1, v2) -> v1)); // key重复取第一个
        // 客户来源
        Map<String, String> bToFromMap = customerList.stream()
                .filter(customer ->
                        customer.get_widget_1722305048887() != null && // 过滤键为null
                                customer.get_widget_1722217596689() != null   // 过滤值为null
                )
                .collect(Collectors.toMap(Customer::get_widget_1722305048887, Customer::get_widget_1722233514707, (v1, v2) -> v1)); // key重复取第一个

        List<Map<String, Object>> mapList = new ArrayList<>();
        // 将处理后的数据存入简道云
        for (DeliveryDocumentsEntity entity : originalData) {
            DeliveryDocumentVO vo = new DeliveryDocumentVO();
            vo.set_widget_1744266564406(entity.getDeliveryDocument());vo.set_widget_1744266564407(entity.getDeliveryDocumentItem());vo.set_widget_1744609087389(entity.getReferenceSDDocument());vo.set_widget_1744784800889(entity.getReferenceSDDocument());vo.set_widget_1744266564409(entity.getReferenceSDDocumentItem());vo.set_widget_1744266564410(entity.getReferenceSDDocumentCategory());
            vo.set_widget_1744266564411(entity.getOverallGoodsMovementStatus());vo.set_widget_1744266564412(entity.getLastChangeDateTime());vo.set_widget_1744266564413(entity.getDeliveryDocumentType());vo.set_widget_1744266564414(entity.getCreationDate());vo.set_widget_1744266564415(entity.getDocumentDate());
            vo.set_widget_1744266564416(entity.getActualGoodsMovementDate());vo.set_widget_1744266564417(entity.getPlannedGoodsIssueDate());vo.set_widget_1744266564418(entity.getSoldToParty());vo.set_widget_1744266564419(entity.getAddressSearchTerm1());vo.set_widget_1744600670161(entity.getYY1_divison_seller_DLH());vo.set_widget_1751677327160(entity.getYY1_divison_seller_DLH());
            vo.set_widget_1744266564421(entity.getSalesOffice());vo.set_widget_1744266564422(entity.getSalesGroup());vo.set_widget_1744266564423(entity.getStorageLocation());vo.set_widget_1744266564424(entity.getYY1_IF_Release_WMS_DLH());vo.set_widget_1744266564425(entity.getYY1_If_Company_Sales_DLI());
            vo.set_widget_1744266564426(entity.getYY1_XXDDBZ_TT_DLH());vo.set_widget_1744266564427(entity.getYY1_XSDDBZ_DLI());
            vo.set_widget_1744266564428(entity.getProduct());vo.set_widget_1744266564429(entity.getBatch());vo.set_widget_1744266564430(entity.getYY1_ZBZXX_SD_DLI());vo.set_widget_1744266564431(entity.getYY1_DeliveryPlant_DLI());
            vo.set_widget_1744266564432(entity.getYY1_ZBMCL_SD_DLI());vo.set_widget_1744266564433(entity.getYY1_ZCL_SD_DLI());vo.set_widget_1744266564434(entity.getYY1_ZGGCC_SD_DLI());vo.set_widget_1744266564435(entity.getYY1_ZCPJZ_SD_DLI());vo.set_widget_1744266564436(entity.getYY1_KS_SD_DLI());
            vo.set_widget_1744266564437(entity.getYY1_ZPJ_SD_DLI());vo.set_widget_1744266564438(entity.getMaterialGroup());vo.set_widget_1744266564439(entity.getYY1_ifvcmaterial_DLI());vo.set_widget_1744266564440(entity.getYY1_WMS_Material_Name_DLI());vo.set_widget_1744266564441(entity.getVcDescription());
            vo.set_widget_1744266564442(entity.getPlant());vo.set_widget_1744266564443(entity.getActualDeliveryQuantity());
            vo.set_widget_1744266564444(entity.getDeliveryQuantityUnit());vo.set_widget_1744266564445(entity.getExchangeRate_a());vo.set_widget_1744266564446(entity.getGroupCurrency());
            vo.set_widget_1744266564447(entity.getExchangeRate_b());vo.set_widget_1744266564448(entity.getCompanyCodeCurrency());vo.set_widget_1744266564449(entity.getConditionRateValue1());vo.set_widget_1744266564450(entity.getNetPriceAmount1());
            vo.set_widget_1744266564451(entity.getNetPriceQuantity());vo.set_widget_1744266564452(entity.getConditionCurrency());vo.set_widget_1744266564453(entity.getNetPriceQuantityUnit());vo.set_widget_1744266564454(entity.getAmount1());
            vo.set_widget_1744266564455(entity.getNetAmount1());vo.set_widget_1744266564456(entity.getAmount2());vo.set_widget_1744266564457(entity.getNetAmount2());vo.set_widget_1744266564458(entity.getAmount3());vo.set_widget_1744266564459(entity.getNetAmount3());
            vo.set_widget_1744266564461(entity.getPlantName());vo.set_widget_1744266564462(entity.getId());vo.set_widget_1744266564463(entity.getBusinessPartnerName1());vo.set_widget_1744266564464(entity.getAddressSearchTerm2());
            vo.set_widget_1744266564465(entity.getCreationDate_1());vo.set_widget_1744266564466(entity.getBusinessPartnerGrouping());vo.set_widget_1744266564467(entity.getYY1_khly_bus());vo.set_widget_1744266564468(entity.getRegion());vo.set_widget_1744266564469(entity.getVcDescription_1());
            vo.set_widget_1763021802059(bToFromMap.get(entity.getSoldToParty())); // 客户来源
            vo.set_widget_1763021802058(materialMap.get(entity.getProduct())); // 物料大类
            vo.set_widget_1763021802057(bToFLMap.get(entity.getProduct())); // 物料分类
            vo.set_widget_1763088136385(salesMaterialToBrandMap.get(entity.getReferenceSDDocument() +"-"+ entity.getProduct())); // 是否自主品牌
            vo.set_widget_1763088937593(bToXHMap.get(entity.getProduct())); // 物料型号


            vo.set_widget_1749632989516(bToCMap.get(entity.getProduct()));
            vo.set_widget_1749632989517(bToTimeMap.get(entity.getSoldToParty()));vo.set_widget_1749632989518(bToCountryMap.get(entity.getSoldToParty()));
            String username = userNameMap.get(vo.get_widget_1744600670161());
            if(("刘晓琪").equals(vo.get_widget_1744600670161())){
                username = "woxjrqDwAAUDe1Gd9cSVXI5sfRaqZ9jQ";
            }
            if (username != null) {
                vo.set_widget_1744600670161(username);
            }
            // 1. 创建表示"2025-06-30"的日期对象（精确到当天结束，即23:59:59.999）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 与字段的timezone保持一致
            Date cutoffDate = null;
            try {
                cutoffDate = sdf.parse("2025-06-30T23:59:59.999Z");
            } catch (ParseException e) {
                e.printStackTrace(); // 处理日期解析异常
            }
            if(entity.getActualGoodsMovementDate() != null && entity.getActualGoodsMovementDate().after(cutoffDate)){
                if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("中非销售")){
                    entity.setSalesOfficeName("BCP中非销售部");
                }else if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("东南亚销售")){
                    entity.setSalesOfficeName("BCP东南亚销售部");
                }else if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("DIY销售部")){
                    entity.setSalesOfficeName("BCP美澳销售部");
                }else if(StringUtils.isNotBlank(entity.getSalesOfficeName()) && entity.getSalesOfficeName().contains("PRO国内销售部")){
                    entity.setSalesOfficeName("PRO亚非销售部");
                }
            }

            // 定义需要特殊处理的a值集合
            Set<String> specialCodes = new HashSet<>(Arrays.asList(
                    "80006813", "80006811", "80006812",
                    "80006809", "80006810", "80006805",
                    "80006808", "80006804", "80005937"
            ));

            String sName = entity.getSalesOfficeName();
            // 判断a是否在特殊值集合中，如果是则设置为BCP东南亚销售部
            if (specialCodes.contains(vo.get_widget_1744266564406())) {
                sName = "BCP东南亚销售部";
            }
            vo.set_widget_1744266564460(sName);

            Integer deptNo = deptMap.get(sName);
            if (deptNo != null) {
                vo.set_widget_1745292386442(deptNo);
            }
            vo.set_id(null);
            mapList.add(ConnmeUtils.convertEntityToMap(vo));

        }
        int batchSize = 100;
        for (int i = 0; i < mapList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, mapList.size());
            List<Map<String, Object>> batchDataIds = mapList.subList(i, endIndex);
            // 存入简道云
            Map<String, Object> parameter = new HashMap<>();
            parameter.put("app_id", appId);
            parameter.put("entry_id", entryId);
            parameter.put("data_list", batchDataIds);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            //log.info("交货单数据批量插入简道云：==== {}", jsonSale);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/batch_create", headers, jsonSale);
        }
        return "success";
    }

    // 深拷贝方法（需要根据实际实体类实现）
    private DeliveryDocumentsEntity cloneEntity(DeliveryDocumentsEntity source) {
        DeliveryDocumentsEntity target = new DeliveryDocumentsEntity();
        BeanUtils.copyProperties(source, target);
        return target;
    }

    private BigDecimal nvl(BigDecimal val) {
        return val != null ? val : BigDecimal.ZERO;
    }



    // 获取物料主数据
    public List<Wuliao01VO> selectList(){
        Header[] headers = ConnmeUtils.createHeaders();
        // 获取到产品主数据数据。
        List<Wuliao01VO> consolidatedOrderVOList = new ArrayList<>();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "668c9750508d1d2bf336211a");
        parameter.put("entry_id", "668c98146b86173be43e6a21");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Wuliao01VO> list = JSONUtil.toList(objects, Wuliao01VO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            consolidatedOrderVOList.addAll(list);
        } while (fale);
        log.info("产品主数据表单数据size：" + consolidatedOrderVOList.size());
        return consolidatedOrderVOList;
    }

    public List<Customer> getCustomerList(){
        List<Customer> customerList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a6f42ff97af74b02d217df");
        parameter.put("entry_id", "66a6f443333584e2c128154f");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Customer> list = JSONUtil.toList(objects, Customer.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            customerList.addAll(list);
        } while (fale);
        return customerList;
    }

    /**
     * 交货单数据【交货单号，交货单金额，销售订单号，销售订单金额】-简道云
     *
     * @return
     */
    @GetMapping("deliverySalesData")
    public String deliverySalesData() {
        List<Map<String, Object>> mapList = new ArrayList<>();
        String appId = "67f8aa2676b9b3942c49035f";
        String entryId = "6858cefa370469b0eea78df5";
        Header[] headers = ConnmeUtils.createHeaders();
        //获取yy1_kpi 表 all数据
        List<YY1_KPI> yy1KpiList = yy1KpiMapper.selectAll();
        // 单句Stream流实现分组求和
        Map<String, BigDecimal> salesDocToTotalAmount = yy1KpiList.stream()
                .collect( Collectors.groupingBy(
                                YY1_KPI::getSalesDocument,
                                Collectors.reducing(
                                        BigDecimal.ZERO,
                                        YY1_KPI::getNetAmount,
                                        BigDecimal::add)));
        // 获取原始交货单数据
        List<DeliveryDocumentsEntity> originalData = yy1KpiMapper.selecDeliveryDocumentsDatatAll();

        List<DeliveryDocumentSummary> documentSummaryList = processDeliveryDataWithPrecision(originalData, salesDocToTotalAmount);
        for (DeliveryDocumentSummary documentSummary : documentSummaryList) {
            DeliverySalesData deliverySalesData = new DeliverySalesData();
            deliverySalesData.set_widget_1750650618091(documentSummary.getDeliveryDocument());
            deliverySalesData.set_widget_1750650618092(documentSummary.getReferenceSDDocuments());
            deliverySalesData.set_widget_1750650618093(documentSummary.getTotalNetAmount());
            deliverySalesData.set_widget_1750650618094(documentSummary.getTotalAmount3());
            deliverySalesData.set_widget_1750747134212(documentSummary.getDeliveryDate());
            deliverySalesData.set_id(null);
            mapList.add(ConnmeUtils.convertEntityToMap(deliverySalesData));
        }
        ConnmeUtils.selectAndDeleteList(headers,appId,entryId,"");
        ConnmeUtils.batchAddList(headers, appId, entryId, mapList);
        return "新增交货单数据【交货单号，交货单金额，销售订单号，销售订单金额】数量："+ documentSummaryList.size() + "条";
    }

    public List<DeliveryDocumentSummary> processDeliveryDataWithPrecision(
            List<DeliveryDocumentsEntity> originalData,
            Map<String, BigDecimal> salesDocToNetAmount) {

        if (originalData == null || salesDocToNetAmount == null) {
            return Collections.emptyList();
        }

        return new ArrayList<>(originalData.stream()
                .collect(Collectors.groupingBy(
                        DeliveryDocumentsEntity::getDeliveryDocument,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                group -> {
                                    String deliveryDoc = group.getFirst().getDeliveryDocument();
                                    Date deliveryDate = group.getFirst().getActualGoodsMovementDate();

                                    Set<String> refDocs = group.stream()
                                            .map(DeliveryDocumentsEntity::getReferenceSDDocument)
                                            .filter(doc -> doc != null && !doc.trim().isEmpty())
                                            .collect(Collectors.toSet());

                                    BigDecimal totalAmount3 = group.stream()
                                            .map(DeliveryDocumentsEntity::getAmount3)
                                            .filter(Objects::nonNull)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add)
                                            .setScale(2, RoundingMode.HALF_UP);  // 保留两位小数

                                    BigDecimal totalNetAmount = refDocs.stream()
                                            .map(salesDocToNetAmount::get)
                                            .filter(Objects::nonNull)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add)
                                            .setScale(2, RoundingMode.HALF_UP);

                                    return new DeliveryDocumentSummary(
                                            deliveryDoc,
                                            String.join("&", refDocs),
                                            totalAmount3,
                                            totalNetAmount,deliveryDate
                                    );
                                }
                        )
                ))
                .values());
    }

    /**
     * 销售和交货单混合取值-数据库
     *
     * @return
     */
    @GetMapping("salesDeliveryData")
    public String salesDeliveryData() {
        // 获取yy1_kpi表all数据（添加非空判断）
        List<YY1_KPI> yy1KpiList = yy1KpiMapper.selectAll();
        if (yy1KpiList == null) {
            yy1KpiList = Collections.emptyList();
        }

        // 获取原始交货单数据（添加非空判断）
        List<DeliveryDocumentsEntity> originalData = yy1KpiMapper.selecDeliveryDocumentsDatatAll();
        if (originalData == null) {
            originalData = Collections.emptyList();
        }

        // 获取最早审核日期
        Map<String, DateTime> salesDocMinDateMap = this.getSalesOrderList().stream()
                .filter(so -> so.getReview_date() != null) // 过滤空日期
                .collect(Collectors.toMap(
                        SalesOrder::get_widget_1718759603973, // 键：销售单号
                        SalesOrder::getReview_date,   // 值：日期
                        BinaryOperator.minBy(Comparator.naturalOrder()) // 冲突时保留较小的日期
                ));
        // 按销售单号分组处理yy1_kpi数据
        Map<String, SalesDeliveryData> resultMap = yy1KpiList.stream()
                .collect(Collectors.groupingBy(YY1_KPI::getSalesDocument))
                .entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> {
                            List<YY1_KPI> group = entry.getValue();
                            SalesDeliveryData data = new SalesDeliveryData();
                            data.setSalesDocument(entry.getKey());

                            // 计算最早/最晚审核时间（添加空值过滤）
                            String minAppTime = String.valueOf(salesDocMinDateMap.get(entry.getKey()));

                            String maxAppTime = group.stream()
                                    .map(YY1_KPI::getYY1_lastapptime_SDH)
                                    .filter(Objects::nonNull)
                                    .max(Comparator.naturalOrder())
                                    .orElse(null);

                            // 计算最早创建时间（添加空值过滤）
                            String minCreateTime = group.stream()
                                    .map(YY1_KPI::getCreationDate)
                                    .filter(Objects::nonNull)
                                    .min(Comparator.naturalOrder())
                                    .orElse(null);

                            // 计算销售数量总和
                            int totalQuantity = group.stream()
                                    .mapToInt(YY1_KPI::getQuantity)
                                    .sum();
                            data.setSalesNum(String.valueOf(totalQuantity));

                            // 计算销售金额总和
                            BigDecimal totalNetAmount = group.stream()
                                    .map(YY1_KPI::getNetAmount)
                                    .filter(Objects::nonNull)
                                    .reduce(BigDecimal.ZERO, BigDecimal::add);
                            data.setSalesMoney(totalNetAmount);

                            // 转换日期格式（添加空值处理）
                            data.setSalesOldAppTime(parseDate(minAppTime));
                            data.setSalesNewAppTime(parseDate(maxAppTime));
                            data.setSalesOldCreateTime(parseDate(minCreateTime));

                            data.setSoldToParty(group.getFirst().getSoldToParty());
                            data.setBusinessPartnerName1(group.getFirst().getBusinessPartnerName1());
                            data.setBusinessPartnerGroupingText(group.getFirst().getBusinessPartnerGroupingText());
                            data.setAuthorizationGroupText(group.getFirst().getAuthorizationGroupText());
                            data.setSalesOfficeName(group.getFirst().getSalesOfficeName());
                            data.setCompanyCodeName(group.getFirst().getCompanyCodeName());
                            data.setRequestedDeliveryDate(parseDate(group.getFirst().getRequestedDeliveryDate()));
                            return data;
                        }
                ));

        // 修复：按销售单号分组处理交货单数据
        Map<String, List<DeliveryDocumentsEntity>> deliveryMap = originalData.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.groupingBy(DeliveryDocumentsEntity::getReferenceSDDocument));

        // 关联交货单数据到销售单
        resultMap.forEach((salesDoc, data) -> {
            List<DeliveryDocumentsEntity> deliveries = deliveryMap.get(salesDoc);
            if (deliveries == null || deliveries.isEmpty()) {
                return;
            }
            // 处理交货单信息
            processDeliveries(data, deliveries);
        });

        yy1KpiMapper.truncateinsertSalesDeliveryData();

        // 数据插入数据库（添加非空判断）
        Collection<SalesDeliveryData> dataList = resultMap.values();
        int insertCount = 0;
        for (SalesDeliveryData data : dataList) {
            if (data != null && data.getSalesDocument() != null) {
                yy1KpiMapper.insertSalesDeliveryData(data);
                insertCount++;
            }
        }

        return "新增数量：" + insertCount + "条";
    }

    /**
     * 处理交货单数据，计算交货相关字段
     */
    private void processDeliveries(SalesDeliveryData data, List<DeliveryDocumentsEntity> deliveries) {
        // 取第一条交货单的编号
        if (!deliveries.isEmpty()) {
            data.setDeliveryDocument(deliveries.getFirst().getDeliveryDocument());
        }

        // 计算最晚交货日期
        Date maxDeliveryTime = deliveries.stream()
                .map(DeliveryDocumentsEntity::getActualGoodsMovementDate)
                .filter(Objects::nonNull)
                .max(Date::compareTo)
                .orElse(null);
        data.setDeliveryNewTime(maxDeliveryTime);

        // 计算交货金额总和
        BigDecimal totalMoney = deliveries.stream()
                .map(DeliveryDocumentsEntity::getAmount3)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        data.setDeliverySumMoney(totalMoney);

        // 计算交货数量总和
        int totalQuantity = deliveries.stream()
                .mapToInt(DeliveryDocumentsEntity::getActualDeliveryQuantity)
                .sum();
        data.setDeliverySumNum(String.valueOf(totalQuantity));
    }

    // 辅助方法：将字符串转换为Date
    private Date parseDate(String dateStr) {
        if ("null".equals(dateStr)) {
            return null;
        }
        if (StringUtils.isBlank(dateStr)) return null;
        try {
            // 使用SimpleDateFormat替代Joda-Time
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return formatter.parse(dateStr);
        } catch (Exception e) {
            log.error("日期解析错误: {}", dateStr, e);
            return null;
        }
    }

    public List<SalesOrder> getSalesOrderList(){
        List<SalesOrder> salesOrderList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "667230ad22a8581756b77d52");
        parameter.put("entry_id", "667230b322a8581756b78353");

        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", "flowState");
        cond.put("type", "flowstate");
        cond.put("method", "eq");
        List<Integer> values = new ArrayList<>();
        values.add(1);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);

        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<SalesOrder> list = JSONUtil.toList(objects, SalesOrder.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            salesOrderList.addAll(list);
        } while (fale);
        return salesOrderList;
    }

}
